/* eslint-disable prettier/prettier */
import React, { useEffect, useState } from 'react';
import { Alert, Image, ImageBackground, Modal, StatusBar, Text, TouchableHighlight, View } from 'react-native';
import styles from './styles';
import { NewWord,GetChaizi } from '../../services/getJsonData';
import {buttons,getbuttons} from '../../services/Randomlist';
import { TouchableOpacity } from 'react-native';
import Sound from 'react-native-sound';
import SoundPlay from '../learn/soundplay';
import getUniqueFileUris from '../learn/getFileList';
import GetjsonData, { Getjsonwords } from '../../services/getJsonData';
import ResultDialog from '../practise/ResultDialog';

const falseSound = new Sound('d.mp3', Sound.MAIN_BUNDLE, (error) => {
  if (error) {
    console.log('failed to load the sound', error);
    return;
  }
  console.log('duration in seconds: ' + falseSound.getDuration() + ' number of channels: ' + falseSound.getNumberOfChannels());
});

const correctSound = new Sound('v.mp3', Sound.MAIN_BUNDLE, (error) => {
  if (error) {
    console.log('failed to load the sound', error);
    return;
  }
  console.log('duration in seconds: ' + correctSound.getDuration() + ' number of channels: ' + correctSound.getNumberOfChannels());
});


const Practise = ({route, navigation}) =>{
  const [huozhong, setHuozhong] = useState<String[]>([]);
  const [characterlist, setCharacterlist] = useState<NewWord[]>([]);
  const [bushou, setBushou] = useState<string[]>([]);
  const [pressbutton, setPressbutton] = useState<buttons[]>([]);
  const [daan, setDaan] = useState<number>(1);
  const [num, setNum] = useState<number>(0);
  const [word, setWord] = useState<string>('dsfs');
  const [succ, setSucc] = useState<number>(4);
  const [fileUris, setFileUris] = useState<{ [key: string]: string }>({});
  const [unit,setUnit] = useState<String>('unit0');
  const [modalVisible, setModalVisible] = useState(false);
    const [success,setSuccess] = useState<boolean>(true);
    const [bgc,setBgc] = useState<String>('asset:/practise_game/practice1_background.jpg');
const [backgroundTransparent, setBackgroundTransparent] = useState('transparent');

  const showResultDialog = () => {
    setModalVisible(true);
    setSuccess(true);
    setBackgroundTransparent('rgba(0, 0, 0, 0.15)'); // 设置背景变暗
  };
  
  const showResultDialogfalse = () => {
    setModalVisible(true);
    setSuccess(false);
    setBackgroundTransparent('0, 0, 0, 0.15'); // 恢复背景透明度
  };

  const init = async ()=>{

    const {unit} = route.params;
    setUnit(unit);
    console.log(unit);
    let m = await Getjsonwords(unit);
    setCharacterlist(m);
    console.log("characterlist:\n" + characterlist);
    let n = await getUniqueFileUris();
    setFileUris(n);
    let o  =  await GetjsonData(unit);
    setHuozhong(o);
    setDaan(daan -1);
    };

useEffect(()=>{
  init();
},[]);
useEffect(() => {
  let level = unit;
  let u = Number(level.slice(-1)) + 1;
  setBgc('asset:/practise_game/practice' + u + '_background.jpg');
},[daan,characterlist,num]);
  useEffect(() => {
  
    console.log(daan + 'sdsd');
  if (daan === 0 ){
   
    console.log(daan);
    let i = num;
      //可选的回调函数，状态更新后执行
     if (characterlist.length > 0 && characterlist.length > num) {
      GetChaizi(characterlist[i]).then(pian => {
              setBushou(pian);
              setDaan(pian.length);
              setWord(characterlist[i].wordName);
                  getbuttons(pian).then(pressbuttons => { // 获取按钮
                      setPressbutton(pressbuttons);
                  });
            });
            console.log('useEffect' + i);
      } else {
        showResultDialog();
      }
  }
}, [daan,characterlist,num]);

const makechoice = (value:string)=>{
  const buttonToChange = pressbutton.find(button => button.title === value);
  if (bushou.includes(value)) {
    if (buttonToChange.value == 0){
      correctSound.play();
      // 当你需要将音频归零时
      correctSound.setCurrentTime(0); // 参数是毫秒，这里设置为 0 毫秒
      buttonToChange.value = 1;
      setDaan(daan - 1);
      console.log('答案正确');
      if (daan <= 1) {
          console.log('答案选择完毕！');
          setNum(num + 1);
        }
    } else { console.log('已经选择！');
              }
  }
  else {
    setSucc(succ - 1 );
    console.log(num); // 现在这里打印的是更新后的值
    if (succ === 0){
      showResultDialogfalse();
    }
    falseSound.play();
    console.log('Value not found in the array.');
  }
  if (daan <= 0){
  }
};
return (
  <ImageBackground
  resizeMode="stretch"
  style={[styles.container, { backgroundColor: backgroundTransparent }]}
  source={{uri: `${bgc}`}}>
  <Text style={styles.wordStyle}>{word}</Text>
  <View style={styles.buttonContainer}>
    {pressbutton.map((pressbuttons) => (
      <TouchableOpacity
        key={pressbuttons.title}
        style={styles.button}
        onPress={() =>makechoice(pressbuttons.title)}>
        <View style={styles.buttonContent}>
          <Image
            source={require('../../src/image/little_ice_cube.png')}
            style={styles.image}
          />
          <Text style={styles.text}>{pressbuttons.title}</Text>
        </View>
      </TouchableOpacity>
    ))}
    <SoundPlay text={fileUris[huozhong[num]] + '.mp3'} isPlaying={true} />
  </View>
  <Modal
animationType="fade"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
  setModalVisible(!modalVisible);
}}
>
<View style={styles.modalContainer}>
  <ResultDialog
    visible={modalVisible}
    success={success}
    toshop={()=>{}}
    tostudy={()=>{navigation.navigate('select');}}
  />
</View>
</Modal>
</ImageBackground>
);
    };
    export default Practise;
